// 上传图片
document.querySelector('.upload').addEventListener('change', function (e) {
    const fd = new FormData
    fd.append('image', e.target.files[0])
    axios({
        url: '/v1_0/upload',
        method: 'post',
        data: fd
    }).then(success => {
        document.querySelector('.upload-img').src = success.data.url
        document.querySelector('.upload-img').style.display = 'block'
        document.querySelector('.icon-addthis').style.zIndex = -1
    }).catch(error => {
        getAlert(document.querySelector('.publish-alert'), '图片太大，请重新选择!', false)
    })
})

// 给发布按钮绑定事件（新增文章）
document.querySelector('.publish-button').addEventListener('click', async function () {
    if (document.querySelector('.edit-input').value !== '') return
    const form = document.querySelector('.publish-form')
    const data = serialize(form, {hash: true, empty: true})
    delete data.id
    data.cover = {
        type: 1, // 封面类型
        images: [document.querySelector('.upload-img').src]// 封面地址
    }
    try {
        const success = await axios({
            url: '/v1_0/mp/articles',
            method: 'post',
            data
        })
        getAlert(document.querySelector('.publish-alert'), '发布文章成功', true)
        // 清空表单
        form.reset()
        // 手动清空图片
        document.querySelector('.upload-img').src = ''
        document.querySelector('.upload-img').style.display = 'none'
        document.querySelector('.icon-addthis').style.zIndex = 1
        // 手动清空富文本编辑器
        editor.setHtml('')
        setTimeout(() => location.href = '../content/index.html', 2000)
    } catch (error) {
        getAlert(document.querySelector('.publish-alert'), '发布文章失败，请检查表单是否有误!', false)
    }
})

// 编辑文章
;(function () {
    // 获取路径参数
    const paramsStr = location.search
    // 将路径参数转换成对象
    const params = new URLSearchParams(paramsStr)
    params.forEach(async (value, key) => {
        if (key === 'id') {
            document.querySelector('.content-manage-title h5').innerHTML = '修改文章'
            document.querySelector('.publish-button').innerHTML = '修改'
            document.querySelector('.edit-article').innerHTML = '修改文章'
            const article = await axios({
                url: `/v1_0/mp/articles/${value}`
            })
            const {title, channel_id, content, id} = article.data
            const uploadImg = article.data.cover.images[0]
            const dataObject = {
                title: title,
                channel_id: channel_id,
                content: content,
                id: id,
                uploadImg: uploadImg
            }
            Object.keys(dataObject).forEach(key => {
                if (key === 'uploadImg'){
                    if (dataObject[key]){
                        // 有封面
                        document.querySelector('.upload-img').src = dataObject[key]
                        document.querySelector('.upload-img').style.display = 'block'
                        document.querySelector('.icon-addthis').style.zIndex = -1
                    }
                }else if (key === 'content'){
                    editor.setHtml(dataObject[key])
                }else {
                    // 用数据对象的属性名，作为标签的name属性选择器 给元素快速赋值
                    document.querySelector(`[name=${key}]`).value = dataObject[key]
                }
            })
        }
    })
})();

// 给修改按钮绑定事件
document.querySelector('.publish-button').addEventListener('click',async function () {
    // 当隐藏表单域的value不等于空时，触发修改按钮事件
    if (document.querySelector('.edit-input').value !== ''){
        console.log(1)
        // 收集数据
        const form = document.querySelector('.publish-form')
        const data = serialize(form, {hash: true, empty: true})
        data.cover = {
            type: 1, // 封面类型
            images: [document.querySelector('.upload-img').src]// 封面地址
        }
        try {
            const success = await axios({
                url: `/v1_0/mp/articles/${data.id}`,
                method:'put',
                data
            })
            getAlert(document.querySelector('.publish-alert'),'修改文章成功',true)
            setTimeout(function (){
                location.href = '../content/index.html'
            },2000)
        }catch (error) {
            getAlert(document.querySelector('.publish-alert'),error.response.data.message,false)
        }
    }
})

